﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using WeifenLuo.WinFormsUI.Docking;
using Infragistics.Win;
using Infragistics.Win.UltraWinGrid;
namespace BYManageInfoSystem
{
    public partial class Frm_FacComeAndGoReg_New : DockContent
    {
       // private const string m_strStartTimeCondition = "' and PaidanRegisterTab.PaiDanDate > '20110630'";
        private const string m_strStartTimeCondition = "'";

        private bool m_bSumStart = false;
        private DGBY.BLL.BGCKHTTab m_bllBGCKHTTab = new DGBY.BLL.BGCKHTTab();
        private DGBY.BLL.FinCheckInvoiceRecordDetailTab_New m_bllFinCheckInvoiceRecordDetailTab_New = new DGBY.BLL.FinCheckInvoiceRecordDetailTab_New();

        private DGBY.BLL.BiZhiTab m_bllBiZhiTab = new DGBY.BLL.BiZhiTab();
        private DGBY.BLL.FactoryDataTab m_bllFactoryDataTab = new DGBY.BLL.FactoryDataTab();
        private DGBY.BLL.FinRecvMoneyDetailTab_New m_bllFinRecvMoneyDetailTab_New = new DGBY.BLL.FinRecvMoneyDetailTab_New();
        private int m_nWholeRecIndex = 0;

        private string m_strBizhiKeep = "";
        private Decimal m_dtRecvMoneyKeep = 0M;
        private Decimal m_dtRecvMoneyHuilv = 0M;
        private Decimal m_dtRMBRecvMoneyHuilv = 0M;
        public Frm_FacComeAndGoReg_New()
        {
            InitializeComponent();
        }

        private void InitCombox()
        {
            DataSet ds = m_bllFactoryDataTab.GetList("");
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                this.comboBoxFac.DataSource = ds.Tables[0];

                this.comboBoxFac.ValueMember = "FactoryDataTabID";
                this.comboBoxFac.DisplayMember = "工厂简称";
                this.comboBoxFac.AutoCompleteSource = AutoCompleteSource.ListItems;
                this.comboBoxFac.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                this.comboBoxFac.SelectedIndex = 0;
            }
        }

        private void Frm_FacComeAndGoReg_New_Load(object sender, EventArgs e)
        {
            InitCombox();
        }
        /// 取得某月的第一天
        /// </summary>
        /// <param name="datetime">要取得月份第一天的时间</param>
        /// <returns></returns>
        private DateTime FirstDayOfMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day);
        }
        /// <summary>
        /// 取得某月的最后一天
        /// </summary>
        /// <param name="datetime">要取得月份最后一天的时间</param>
        /// <returns></returns>
        private DateTime LastDayOfMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1);
        }

        private Decimal ComputeRevMoneyByDate(string strWhere)
        {
            Decimal dtTotal = 0;
            DataSet ds = m_bllFinRecvMoneyDetailTab_New.GetList(strWhere);
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    Decimal dtTemp = (Decimal)ds.Tables[0].Rows[i]["扣费后折算为USD"];
                    

                    dtTotal += dtTemp;
                }
            }
            return dtTotal;
        }

        private Decimal ComputeChuKouJinEByDate(string strWhere)
        {
            Decimal dtTotal = 0;
            DataSet ds = m_bllBGCKHTTab.GetChuKouRecordTabInfo(strWhere);
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    Decimal dtTemp = (Decimal)ds.Tables[0].Rows[i]["报关金额"];
                    dtTotal += dtTemp;
                }
            }
            return dtTotal;
        }
        private List<string> ListCountAllCKHTMXForBackTax(string strWhere)
        {
            List<string> lstMoreBackTaxPointContract = new List<string>();
            DataSet ds = m_bllBGCKHTTab.ListCountAllCKHTMXForBackTax(strWhere);

            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {

                for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
                {
                    string strContract = ds.Tables[0].Rows[j]["合同号"].ToString();
                    lstMoreBackTaxPointContract.Add(strContract);
                }
            }

            return lstMoreBackTaxPointContract;
        }
        private Dictionary<string, Decimal> ListSingleCKHTMXForBackTax(string strWhere)
        {
            Dictionary<string, Decimal> DicContractNo2SingleBackTaxPoint = new Dictionary<string, Decimal>();
            DataSet ds = m_bllBGCKHTTab.ListSingleCKHTMXForBackTax(strWhere);

            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {

                for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
                {
                    string strContract = ds.Tables[0].Rows[j]["合同号"].ToString();
                    Decimal dtTemp = (Decimal)ds.Tables[0].Rows[j]["退税点"];

                    DicContractNo2SingleBackTaxPoint.Add(strContract, dtTemp);
                }
            }

            return DicContractNo2SingleBackTaxPoint;
        }
        private void buttonQuery_Click(object sender, EventArgs e)
        {
            m_strBizhiKeep = "";
            m_dtRecvMoneyKeep = 0M;
            m_dtRecvMoneyHuilv = 0M;
            m_dtRMBRecvMoneyHuilv = 0M;
            //截止查询开始时间出口金额总值
            Decimal dtChuKouTotal = ComputeChuKouJinEByDate("FactoryDataTab.FactoryDataTabID = '" + this.comboBoxFac.SelectedValue + m_strStartTimeCondition);
            //截止查询开始时间收款总值
            Decimal dtRecvMoneyTotal = ComputeRevMoneyByDate(" 客户 = '" + this.comboBoxFac.SelectedValue + m_strStartTimeCondition);
                                    
           
            this.textBoxLastJinE.Text = "";



            this.textBoxBetween.Text = (dtRecvMoneyTotal - dtChuKouTotal).ToString();


            this.textBoxChuKouTotal.Text = dtChuKouTotal.ToString();

            this.textBoxRecvMoneyTotal.Text = dtRecvMoneyTotal.ToString();
            ShowAllRecordInDataGridView();
           // ShowAllRecordInDataGridView("", dtDiffFrom, dtChouKouTotal);
        }

        private void AddNewColumn(DataTable dt)
        {
            int nIndex = 0;
            dt.Columns.Add("收款RMB汇率", System.Type.GetType("System.Decimal"));
            dt.Columns["收款RMB汇率"].SetOrdinal(nIndex++);

            dt.Columns.Add("合同号", System.Type.GetType("System.String"));
            dt.Columns["合同号"].SetOrdinal(nIndex++);
            dt.Columns.Add("申报日期", System.Type.GetType("System.DateTime"));
            dt.Columns["申报日期"].SetOrdinal(nIndex++);
            dt.Columns.Add("币制", System.Type.GetType("System.String"));
            dt.Columns["币制"].SetOrdinal(nIndex++);
            dt.Columns.Add("出口总金额", System.Type.GetType("System.Decimal"));
            dt.Columns["出口总金额"].SetOrdinal(nIndex++);
            dt.Columns.Add("出口金额设17%", System.Type.GetType("System.Decimal"));
            dt.Columns["出口金额设17%"].SetOrdinal(nIndex++);
            dt.Columns.Add("出口金额设16%", System.Type.GetType("System.Decimal"));
            dt.Columns["出口金额设16%"].SetOrdinal(nIndex++);
            dt.Columns.Add("出口金额设15%", System.Type.GetType("System.Decimal"));
            dt.Columns["出口金额设15%"].SetOrdinal(nIndex++);
            dt.Columns.Add("出口金额设13%", System.Type.GetType("System.Decimal"));
            dt.Columns["出口金额设13%"].SetOrdinal(nIndex++);
            dt.Columns.Add("出口金额设9%", System.Type.GetType("System.Decimal"));
            dt.Columns["出口金额设9%"].SetOrdinal(nIndex++);
            dt.Columns.Add("出口金额设5%", System.Type.GetType("System.Decimal"));
            dt.Columns["出口金额设5%"].SetOrdinal(nIndex++);

            dt.Columns.Add("是否开票", System.Type.GetType("System.String"));
            dt.Columns["是否开票"].SetOrdinal(nIndex++);

            dt.Columns.Add("结汇日期", System.Type.GetType("System.DateTime"));
            dt.Columns["结汇日期"].SetOrdinal(nIndex++);
            dt.Columns.Add("收款币种", System.Type.GetType("System.String"));
            dt.Columns["收款币种"].SetOrdinal(nIndex++);
            dt.Columns.Add("折算为USD", System.Type.GetType("System.Decimal"));
            dt.Columns["折算为USD"].SetOrdinal(nIndex++);

            //dt.Columns.Add("收款金额设17%", System.Type.GetType("System.Decimal"));
            //dt.Columns["收款金额设17%"].SetOrdinal(nIndex++);
            //dt.Columns.Add("收款金额设16%", System.Type.GetType("System.Decimal"));
            //dt.Columns["收款金额设16%"].SetOrdinal(nIndex++);
            //dt.Columns.Add("收款金额设15%", System.Type.GetType("System.Decimal"));
            //dt.Columns["收款金额设15%"].SetOrdinal(nIndex++);
            //dt.Columns.Add("收款金额设13%", System.Type.GetType("System.Decimal"));
            //dt.Columns["收款金额设13%"].SetOrdinal(nIndex++);
            //dt.Columns.Add("收款金额设9%", System.Type.GetType("System.Decimal"));
            //dt.Columns["收款金额设9%"].SetOrdinal(nIndex++);
            //dt.Columns.Add("收款金额设5%", System.Type.GetType("System.Decimal"));
            //dt.Columns["收款金额设5%"].SetOrdinal(nIndex++);


            dt.Columns.Add("RMB汇率", System.Type.GetType("System.Decimal"));
            dt.Columns["RMB汇率"].SetOrdinal(nIndex++);
            dt.Columns.Add("付本日期", System.Type.GetType("System.DateTime"));
            dt.Columns["付本日期"].SetOrdinal(nIndex++);

            dt.Columns.Add("已付货款", System.Type.GetType("System.Decimal"));
            dt.Columns["已付货款"].SetOrdinal(nIndex++);
            dt.Columns.Add("付税日期", System.Type.GetType("System.DateTime"));
            dt.Columns["付税日期"].SetOrdinal(nIndex++);

            dt.Columns.Add("已付税汇率", System.Type.GetType("System.Decimal"));
            dt.Columns["已付税汇率"].SetOrdinal(nIndex++);
            dt.Columns.Add("已付税", System.Type.GetType("System.Decimal"));
            dt.Columns["已付税"].SetOrdinal(nIndex++);
            dt.Columns.Add("已付税计算公式", System.Type.GetType("System.String"));
            dt.Columns["已付税计算公式"].SetOrdinal(nIndex++);
            dt.Columns.Add("系数A", System.Type.GetType("System.Decimal"));
            dt.Columns["系数A"].SetOrdinal(nIndex++);
            dt.Columns.Add("系数B", System.Type.GetType("System.Decimal"));
            dt.Columns["系数B"].SetOrdinal(nIndex++);

            dt.Columns.Add("付税本金", System.Type.GetType("System.Decimal"));
            dt.Columns["付税本金"].SetOrdinal(nIndex++);
            dt.Columns.Add("设定开票汇率", System.Type.GetType("System.Decimal"));
            dt.Columns["设定开票汇率"].SetOrdinal(nIndex++);
            dt.Columns.Add("开票本金", System.Type.GetType("System.Decimal"));
            dt.Columns["开票本金"].SetOrdinal(nIndex++);
            dt.Columns.Add("补RMB", System.Type.GetType("System.Decimal"));
            dt.Columns["补RMB"].SetOrdinal(nIndex++);
            dt.Columns.Add("应退税额", System.Type.GetType("System.Decimal"));
            dt.Columns["应退税额"].SetOrdinal(nIndex++);
        }

        private void FillTax(DataTable dtNew
            , int nFormulaSelector, Decimal dtFactorA
            , Decimal dtBackTaxPoint, Decimal dtRecvMoneyOrig
            , string strBizhi, Decimal dtRecvMoneyHuilv, Decimal dtRecvMoneyRMBHuilv)
        {
            try
            {
                string strPayTaxBenJinGongShiTemp = "";
                if (nFormulaSelector == 0)
                {
                    if (strBizhi == "USD")
                    {
                        if (m_nWholeRecIndex == 31)
                        {
                            Decimal dtTemp3 = (Decimal)dtNew.Rows[m_nWholeRecIndex - 1]["付税本金"];
                            Decimal dtTemp = (Decimal)dtNew.Rows[m_nWholeRecIndex - 1]["已付税汇率"];
                            
                        }
                        
                        dtNew.Rows[m_nWholeRecIndex - 1]["已付税"]
                            = ((Decimal)dtNew.Rows[m_nWholeRecIndex - 1]["已付税汇率"] - dtFactorA) * 1.17M
                            * (Decimal)dtNew.Rows[m_nWholeRecIndex - 1]["付税本金"] / (1.17M - dtBackTaxPoint)
                            - (Decimal)dtNew.Rows[m_nWholeRecIndex - 1]["付税本金"] * (Decimal)dtNew.Rows[m_nWholeRecIndex - 1]["已付税汇率"];

                        strPayTaxBenJinGongShiTemp = " ( " + dtRecvMoneyOrig.ToString("0.00") + " - "
                            + (dtRecvMoneyOrig - (Decimal)dtNew.Rows[m_nWholeRecIndex - 1]["付税本金"]).ToString("0.00")
                            + " ) * " +
                            " ( " + dtNew.Rows[m_nWholeRecIndex - 1]["已付税汇率"].ToString()
                            + " - " + dtFactorA.ToString("0.000") + ") * 1.17 "
                            + " / " + (1.17M - dtBackTaxPoint).ToString("0.00") + " - " + ((Decimal)dtNew.Rows[m_nWholeRecIndex - 1]["付税本金"]).ToString("0.00")
                            + " * " + dtNew.Rows[m_nWholeRecIndex - 1]["已付税汇率"].ToString();
                    }
                    else
                    {
                        if (1.17M - dtBackTaxPoint > 0 && dtRecvMoneyHuilv > 0)
                        {
                            dtNew.Rows[m_nWholeRecIndex - 1]["已付税"]
                               = ((Decimal)dtNew.Rows[m_nWholeRecIndex - 1]["已付税汇率"] - dtFactorA) * 1.17M
                               * (Decimal)dtNew.Rows[m_nWholeRecIndex - 1]["付税本金"] / (1.17M - dtBackTaxPoint)
                               - (Decimal)dtNew.Rows[m_nWholeRecIndex - 1]["付税本金"] * (Decimal)dtNew.Rows[m_nWholeRecIndex - 1]["已付税汇率"];

                            strPayTaxBenJinGongShiTemp
                                = " ( " + (dtRecvMoneyOrig / dtRecvMoneyHuilv).ToString("0.00")
                                + " - " + ((dtRecvMoneyOrig - (Decimal)dtNew.Rows[m_nWholeRecIndex - 1]["付税本金"]) / dtRecvMoneyHuilv).ToString("0.00")
                                + " ) * " + dtRecvMoneyRMBHuilv.ToString() + " / " + dtNew.Rows[m_nWholeRecIndex - 1]["已付税汇率"].ToString() +
                                " * ( " + dtNew.Rows[m_nWholeRecIndex - 1]["已付税汇率"].ToString()
                                + " - " + dtFactorA.ToString("0.000") + ") * 1.17 "
                                + " / " + (1.17M - dtBackTaxPoint).ToString("0.00")
                                + " - " + ((Decimal)dtNew.Rows[m_nWholeRecIndex - 1]["付税本金"] / dtRecvMoneyHuilv).ToString("0.00")
                                + " * " + dtRecvMoneyRMBHuilv.ToString(); ;
                        }
                        else
                        {
                            strPayTaxBenJinGongShiTemp = "";
                        }
                    }
                }
                else
                {
                    dtNew.Rows[m_nWholeRecIndex - 1]["已付税"] = (Decimal)dtNew.Rows[m_nWholeRecIndex - 1]["付税本金"]
                        * dtFactorA * (Decimal)dtNew.Rows[m_nWholeRecIndex - 1]["已付税汇率"];

                    strPayTaxBenJinGongShiTemp = dtNew.Rows[m_nWholeRecIndex - 1]["付税本金"].ToString()
                        + " * " + dtFactorA.ToString() + " * " + dtNew.Rows[m_nWholeRecIndex - 1]["已付税汇率"].ToString();
                }
                dtNew.Rows[m_nWholeRecIndex - 1]["已付税计算公式"] = strPayTaxBenJinGongShiTemp;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            
        }

        private void ProcessBackTax(DataTable dtNew, ArrayList alInvoice
            , DataTable DataTableInvoice, ArrayList alInvoiceIndex
            , int nFormulaSelector, Decimal dtFactorA, DataRow drRecv)
        {
            try
            {
                if (alInvoice.Count == 0)
                    return;
                int nInvoiceIndex = (int)alInvoiceIndex[0];
                DateTime dateTemp = (DateTime)DataTableInvoice.Rows[nInvoiceIndex]["PayTaxDate"];
                Decimal dtBackTaxPoint = (Decimal)DataTableInvoice.Rows[nInvoiceIndex]["PayTaxPercent"];

                Decimal dtRecvMoneyHuilv = 0M;
                Decimal dtRecvMoneyOrig = 0M;
                Decimal dtRecvMoneyRMBHuilv = 0M;
                string strBizhi = "";
                string strRecvMoney = dtNew.Rows[m_nWholeRecIndex - 1]["折算为USD"].ToString();

                if (strRecvMoney == "")
                {
                    strBizhi = m_strBizhiKeep;
                    dtRecvMoneyOrig = m_dtRecvMoneyKeep;
                    dtRecvMoneyHuilv = m_dtRecvMoneyHuilv;
                    dtRecvMoneyRMBHuilv = m_dtRMBRecvMoneyHuilv;
                }
                else
                {
                    dtRecvMoneyRMBHuilv = (Decimal)drRecv["RMB汇率"];
                    dtRecvMoneyHuilv = (Decimal)drRecv["汇率"];
                    dtRecvMoneyOrig = (Decimal)drRecv["折算为USD"];
                    strBizhi = dtNew.Rows[m_nWholeRecIndex - 1]["收款币种"].ToString();
                    m_strBizhiKeep = strBizhi;
                    m_dtRecvMoneyKeep = dtRecvMoneyOrig;
                    m_dtRecvMoneyHuilv = dtRecvMoneyHuilv;
                    m_dtRMBRecvMoneyHuilv = dtRecvMoneyRMBHuilv;
                }
                Decimal dtRecvMoney = (Decimal)dtNew.Rows[m_nWholeRecIndex - 1]["折算为USD"];
                Decimal dtInvoice = (Decimal)alInvoice[0];

                if (dtRecvMoney < dtInvoice)
                {
                    dtNew.Rows[m_nWholeRecIndex - 1]["付税本金"] = dtRecvMoney;
                    dtNew.Rows[m_nWholeRecIndex - 1]["付税日期"] = dateTemp;
                    dtNew.Rows[m_nWholeRecIndex - 1]["系数B"] = dtBackTaxPoint;
                    dtNew.Rows[m_nWholeRecIndex - 1]["已付税汇率"] = dtNew.Rows[m_nWholeRecIndex - 1]["RMB汇率"];

                    FillTax(dtNew, nFormulaSelector, dtFactorA, dtBackTaxPoint
                        , dtRecvMoneyOrig, strBizhi, dtRecvMoneyHuilv, dtRecvMoneyRMBHuilv);


                    dtInvoice -= dtRecvMoney;
                    alInvoice.RemoveAt(0);
                    alInvoice.Insert(0, dtInvoice);
                }
                else if (dtRecvMoney == dtInvoice)
                {
                    dtNew.Rows[m_nWholeRecIndex - 1]["付税本金"] = dtRecvMoney;
                    dtNew.Rows[m_nWholeRecIndex - 1]["付税日期"] = dateTemp;
                    dtNew.Rows[m_nWholeRecIndex - 1]["系数B"] = dtBackTaxPoint;
                    dtNew.Rows[m_nWholeRecIndex - 1]["已付税汇率"] = dtNew.Rows[m_nWholeRecIndex - 1]["RMB汇率"];
                    FillTax(dtNew, nFormulaSelector, dtFactorA
                        , dtBackTaxPoint, dtRecvMoneyOrig
                        , strBizhi, dtRecvMoneyHuilv, dtRecvMoneyRMBHuilv);
                    alInvoice.RemoveAt(0);
                    alInvoiceIndex.RemoveAt(0);
                }
                else//dtRecvMoney > dtInvoice
                {
                    while (dtRecvMoney >= dtInvoice)
                    {
                        nInvoiceIndex = (int)alInvoiceIndex[0];
                        dateTemp = (DateTime)DataTableInvoice.Rows[nInvoiceIndex]["PayTaxDate"];
                        dtBackTaxPoint = (Decimal)DataTableInvoice.Rows[nInvoiceIndex]["PayTaxPercent"];
                        dtNew.Rows[m_nWholeRecIndex - 1]["付税本金"] = dtInvoice;
                        dtNew.Rows[m_nWholeRecIndex - 1]["付税日期"] = dateTemp;
                        dtNew.Rows[m_nWholeRecIndex - 1]["系数B"] = dtBackTaxPoint;
                        if (dtNew.Rows[m_nWholeRecIndex - 1]["RMB汇率"].ToString() == "")
                        {
                            dtNew.Rows[m_nWholeRecIndex - 1]["已付税汇率"] = dtNew.Rows[m_nWholeRecIndex - 2]["已付税汇率"];
                        }
                        else
                        {
                            dtNew.Rows[m_nWholeRecIndex - 1]["已付税汇率"] = dtNew.Rows[m_nWholeRecIndex - 1]["RMB汇率"];

                        }
                        FillTax(dtNew, nFormulaSelector, dtFactorA
                            , dtBackTaxPoint, dtRecvMoneyOrig
                            , strBizhi, dtRecvMoneyHuilv, dtRecvMoneyRMBHuilv);
                        alInvoice.RemoveAt(0);
                        alInvoiceIndex.RemoveAt(0);
                        dtRecvMoney = dtRecvMoney - dtInvoice;
                        if (alInvoice.Count > 0 && dtRecvMoney > 0)
                        {
                            dtInvoice = (Decimal)alInvoice[0];
                            m_nWholeRecIndex++;
                            DataRow dr = dtNew.NewRow();
                            dtNew.Rows.Add(dr);
                       
                        }
                        else
                            break;
                    }

                    if (alInvoice.Count > 0 && dtRecvMoney > 0)
                    {
                        nInvoiceIndex = (int)alInvoiceIndex[0];
                        dateTemp = (DateTime)DataTableInvoice.Rows[nInvoiceIndex]["PayTaxDate"];
                        dtBackTaxPoint = (Decimal)DataTableInvoice.Rows[nInvoiceIndex]["PayTaxPercent"];
                        dtNew.Rows[m_nWholeRecIndex - 1]["付税本金"] = dtRecvMoney;
                        dtNew.Rows[m_nWholeRecIndex - 1]["付税日期"] = dateTemp;
                        dtNew.Rows[m_nWholeRecIndex - 1]["系数B"] = dtBackTaxPoint;
                        if (m_nWholeRecIndex == 31)
                        {
                            int a = 0;
                        }
                        int nRecIndexTemp = m_nWholeRecIndex;

                        while (dtNew.Rows[nRecIndexTemp - 1]["RMB汇率"].ToString() == "")
                        {
                            nRecIndexTemp--;
                        }

                        dtNew.Rows[m_nWholeRecIndex - 1]["已付税汇率"] = dtNew.Rows[nRecIndexTemp - 1]["RMB汇率"];

                        //if (dtNew.Rows[m_nWholeRecIndex - 1]["RMB汇率"].ToString() == "")
                        //{
                        //    dtNew.Rows[m_nWholeRecIndex - 1]["已付税汇率"] = dtNew.Rows[m_nWholeRecIndex - 2]["RMB汇率"];
                        //}
                        //else
                        //{
                        //    dtNew.Rows[m_nWholeRecIndex - 1]["已付税汇率"] = dtNew.Rows[m_nWholeRecIndex - 1]["RMB汇率"];

                        //}

                        FillTax(dtNew, nFormulaSelector, dtFactorA
                            , dtBackTaxPoint, dtRecvMoneyOrig
                            , strBizhi, dtRecvMoneyHuilv, dtRecvMoneyRMBHuilv);
                        dtInvoice -= dtRecvMoney;
                        alInvoice.RemoveAt(0);
                        alInvoice.Insert(0, dtInvoice);
                    }
                }

                return;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            
            //int nInvoiceRecCounts = drInvoiceRows.Count();
            //int nRecvMoneyRecCounts = m_nWholeRecIndex - nLastUltragridChuKouRowIndexRec + 1;

       
            //Decimal dtTempAccu = 0;


            //int nMax = Math.Max(nInvoiceRecCounts, nRecvMoneyRecCounts);
            //int nIndex = 1;
            //Decimal dtInvoiceTemp = GetInvoiceValue(drInvoiceRows, dtNew, nLastUltragridChuKouRowIndexRec
            //    , nIndex, dtTempAccu);//到nIndex为止，去掉累积的数值
            //Decimal dtRecvMoneyTmp = GetRecvMoney(dtNew, nLastUltragridChuKouRowIndexRec
            //    , nIndex, dtTempAccu, nRecvMoneyRecCounts);//到nIndex为止，去掉累积的数值
            //while (nIndex <= nMax && dtInvoiceTemp > 0 && dtRecvMoneyTmp > 0)
            //{
            //    dtInvoiceTemp = GetInvoiceValue(drInvoiceRows, dtNew, nLastUltragridChuKouRowIndexRec
            //        , nIndex, dtTempAccu);//到nIndex为止，去掉累积的数值
            //    dtRecvMoneyTmp = GetRecvMoney(dtNew, nLastUltragridChuKouRowIndexRec
            //        , nIndex, dtTempAccu, nRecvMoneyRecCounts);

            //    Decimal dtBackTaxBenJin = 0;
            //    if (dtInvoiceTemp > dtRecvMoneyTmp)
            //    {
            //        dtBackTaxBenJin = dtInvoiceTemp - dtRecvMoneyTmp;
            //    }
            //    else
            //    {
            //        dtBackTaxBenJin = dtRecvMoneyTmp - dtInvoiceTemp;
            //    }

            //    dtTempAccu += dtBackTaxBenJin;
            //    nIndex++;
            //}
        }
        //到nIndex为止的累加值去掉累积的数值 dtAccu       
        private Decimal GetInvoiceValue(DataRow[] drInvoiceRows, DataTable dtNew
            , int nBaseIndex, int nIndex, Decimal dtAccu)
        {
            Decimal dtRet = 0;
            try
            {
               
                int nTempTotalRows = Math.Max(nIndex, drInvoiceRows.Count());
                int nBegin = nBaseIndex;
                int nEnd = nBaseIndex + nTempTotalRows;
                while (nBegin <= nEnd)
                {
                    dtRet += (Decimal)drInvoiceRows[nBegin]["折算为USD"];

                    nBegin++;
                }
                dtRet -= dtAccu;
            }
            catch (Exception ex)
            {
            }

            return dtRet;
           
        }
        //到nIndex为止的累加值去掉累积的数值 dtAccu    
        private Decimal GetRecvMoney(DataTable dtNew, int nBaseIndex, int nIndex, Decimal dtAccu, int nTotalRows)
        {
            Decimal dtRet = 0;
            int nTempTotalRows = Math.Max(nIndex, nTotalRows);
            int nBegin = nBaseIndex;
            int nEnd = nBaseIndex + nTempTotalRows;
            string strBizhiName = dtNew.Rows[nBegin]["币制"].ToString();
            Decimal dtUsdHuiLv = (Decimal)dtNew.Rows[nBegin]["美元汇率"];
            Decimal dtHKHuiLv = (Decimal)dtNew.Rows[nBegin]["港币汇率"];
            while (nBegin <= nEnd)
            {
                if (strBizhiName == "美元")
                {
                    dtRet += (Decimal)dtNew.Rows[nBegin]["开票USD设17"]
                        + (Decimal)dtNew.Rows[nBegin]["开票USD设16"]
                        + (Decimal)dtNew.Rows[nBegin]["开票USD设15"]
                        + (Decimal)dtNew.Rows[nBegin]["开票USD设13"]
                        + (Decimal)dtNew.Rows[nBegin]["开票USD设9"]
                        + (Decimal)dtNew.Rows[nBegin]["开票USD设5"];
                }
                else if (strBizhiName == "港币")
                {
                    if (dtHKHuiLv == 0)
                        dtRet += 0;
                    else
                        dtRet += ((Decimal)dtNew.Rows[nBegin]["开票USD设17"]
                            + (Decimal)dtNew.Rows[nBegin]["开票USD设16"]
                            + (Decimal)dtNew.Rows[nBegin]["开票USD设15"]
                            + (Decimal)dtNew.Rows[nBegin]["开票USD设13"]
                            + (Decimal)dtNew.Rows[nBegin]["开票USD设9"]
                            + (Decimal)dtNew.Rows[nBegin]["开票USD设5"]) * dtHKHuiLv / dtUsdHuiLv;
                }


                nBegin++;
            }
            dtRet -= dtAccu;
            return dtRet;
        }

        private void FillBackTaxPointJinETrue(Decimal dtBackTaxPoint, Decimal dtJinE, DataRow dr)
        {
            Decimal dtDiff = 1.17M - dtBackTaxPoint;
            int nDiff = (int)(dtDiff * 100);
            if (nDiff != 17 && nDiff != 16 && nDiff != 15
                && nDiff != 13 && nDiff != 9 && nDiff != 5)
                return;
            string strCompose = "出口金额设" + nDiff.ToString() + "%";
            dr[strCompose] = dtJinE;
        }

        private void FillBackTaxPointJinE(DataSet dsTemp, DataRow dr)
        {
            if (dsTemp.Tables.Count > 0 && dsTemp.Tables[0].Rows.Count > 1)
            {
                for (int i = 0; i < dsTemp.Tables[0].Rows.Count; i++)
                {
                    Decimal dtBackTaxPoint = (Decimal)dsTemp.Tables[0].Rows[i]["退税点"];
                    
                    Decimal dtTemp = (Decimal)dsTemp.Tables[0].Rows[i]["金额"];
                    FillBackTaxPointJinETrue(dtBackTaxPoint, dtTemp, dr);
                }


            }
        }

        private void ShowAllRecordInDataGridView()
        {
            try
            {
                Decimal dtRecvMoneyKeepRec = 0;
                Decimal dtChuKouJinEKeepRec = 0;
                int nChuKouRowIndexRec = 0;//dataset里的游标
                int nLastUltragridChuKouRowIndexRec = 0;//Ultragrid里的游标
                int nRecvMoneyRowIndexRec = 0;
                DataTable dtNew = new DataTable();
                AddNewColumn(dtNew);
                ultraGrid1.DataSource = null;
                ultraGrid1.DataSource = dtNew;
                ultraGrid1.DisplayLayout.Bands[0].Columns[0].Hidden = true;

                int nChuKouRowIndex = 0;//dataset里的移动游标
                int nRecvMoneyRowIndex = 0;
                m_nWholeRecIndex = 0;


                DataSet dsChuKou
                  = m_bllBGCKHTTab.GetChuKouRecordTabInfo(" FactoryDataTab.FactoryDataTabID = '"
                  + this.comboBoxFac.SelectedValue + m_strStartTimeCondition
                  + " and PaidanRegisterTab.PaidanRegisterTabID in (select HxdNoTab.PaidanRegisterTabID from HxdNoTab) ");

                //foreach(string strColumn in dsChuKou.Tables[0].Columns)

                int nFormulaSelector = -1;
                Decimal dtFactorA = 0;
               // DataTable dt = SelectDistinct("dsChuKou", dsChuKou.Tables[0], "合同号");
                if (dsChuKou.Tables.Count <= 0 || dsChuKou.Tables[0].Rows.Count <= 0)
                {
                    return;
                }
                else
                {
                    nFormulaSelector = (int)dsChuKou.Tables[0].Rows[0]["公式选择"];
                    dtFactorA = (Decimal)dsChuKou.Tables[0].Rows[0]["系数A"];
                }
                //用来除去重复行
                List<string> lstContractNo = new List<string>();
                List<int> lstIntRemoveIndex = new List<int>();
                //for (int v = dsChuKou.Tables[0].Rows.Count - 1; v >= 0; v--)
                for (int v = 0; v < dsChuKou.Tables[0].Rows.Count; v++)
                {
                    string strConNo = dsChuKou.Tables[0].Rows[v]["合同号"].ToString();
                    if(lstContractNo.Contains(strConNo))
                    {
                        //dsChuKou.Tables[0].Rows.RemoveAt(v);
                        lstIntRemoveIndex.Add(v);
                        continue;
                    }
                    
                    lstContractNo.Add(strConNo);
                }

                for (int v = dsChuKou.Tables[0].Rows.Count - 1; v >= 0; v--)
                {
                    if (lstIntRemoveIndex.Contains(v))
                    {
                        dsChuKou.Tables[0].Rows.RemoveAt(v);
                    }
                   
                }
                //for (int v = 0; j < dsInvoice.Tables[0].Rows.Count; j++)
                //{
                //}


                DataSet dsRecvMoney 
                    = m_bllFinRecvMoneyDetailTab_New.GetListBiZhiString(" 客户 = '" + this.comboBoxFac.SelectedValue 
                    + m_strStartTimeCondition);


                if (dsRecvMoney.Tables.Count <= 0 || dsRecvMoney.Tables[0].Rows.Count <= 0)
                {
                    //return;
                }
                //该工厂的全部审过票的审票金额集合
                ArrayList alInvoice = new ArrayList();
                ArrayList alInvoiceIndex = new ArrayList();
                DataSet dsInvoice
                    = m_bllFinCheckInvoiceRecordDetailTab_New.GetFinInvoiceRecordTabInfoComeAndGoNew(
                    "FinCheckInvoiceRecordDetailAuxiliaryTab_New.SubSeqNo = 0 and FactoryDataTab.FactoryNameJX = '" + this.comboBoxFac.Text 
                    + m_strStartTimeCondition);

                for (int j = 0; j < dsInvoice.Tables[0].Rows.Count; j++)
                {
                    Decimal dtTemp = (Decimal)dsInvoice.Tables[0].Rows[j]["PayTaxMoneyValue"];
                        //+ (Decimal)dsInvoice.Tables[0].Rows[j]["开票USD设16"]
                        //+ (Decimal)dsInvoice.Tables[0].Rows[j]["开票USD设15"]
                        //+ (Decimal)dsInvoice.Tables[0].Rows[j]["开票USD设13"]
                        //+ (Decimal)dsInvoice.Tables[0].Rows[j]["开票USD设9"]
                        //+ (Decimal)dsInvoice.Tables[0].Rows[j]["开票USD设5"];
                     
                    alInvoice.Add(dtTemp);
                    alInvoiceIndex.Add(j);
                }

                //退税点多于一个的合同集合
                List<string> lstMoreBackTaxPointContract 
                    = ListCountAllCKHTMXForBackTax("FactoryDataTab.FactoryNameJX = '"
                    + this.comboBoxFac.Text + m_strStartTimeCondition);

                //单退税点合同号2退税点字典
                Dictionary<string, Decimal> DicContractNo2SingleBackTaxPoint 
                    = ListSingleCKHTMXForBackTax("FactoryDataTab.FactoryNameJX = '"
                    + this.comboBoxFac.Text + m_strStartTimeCondition);


                Decimal dtFinalRecvTemp = 0;
                while (nChuKouRowIndex < dsChuKou.Tables[0].Rows.Count
                    && nRecvMoneyRowIndex < dsRecvMoney.Tables[0].Rows.Count)
                {
                    //if(m_nWholeRecIndex > 0)
                    //    ProcessBackTax(dtNew, alInvoice
                    //        , dsInvoice.Tables[0], alInvoiceIndex, nFormulaSelector,dtFactorA);

                    Decimal dtChuKouJinETemp = 0;
                    Decimal dtRecvMoneyTemp = 0;


                    ////如果是出口是第一条记录
                    if (nChuKouRowIndex == 0 && m_nWholeRecIndex == 0)
                    {
                        dtChuKouJinETemp = (Decimal)dsChuKou.Tables[0].Rows[nChuKouRowIndex]["报关金额"];
                        nRecvMoneyRowIndexRec = nRecvMoneyRowIndex;
                        nLastUltragridChuKouRowIndexRec = m_nWholeRecIndex;

                        DataRow dr = dtNew.NewRow();
                        dtNew.Rows.Add(dr);

                        dtNew.Rows[m_nWholeRecIndex]["合同号"] = dsChuKou.Tables[0].Rows[nChuKouRowIndex]["合同号"];
                        dtNew.Rows[m_nWholeRecIndex]["申报日期"] = dsChuKou.Tables[0].Rows[nChuKouRowIndex]["申报日期"];
                        dtNew.Rows[m_nWholeRecIndex]["币制"] = dsChuKou.Tables[0].Rows[nChuKouRowIndex]["币制"];
                        dtNew.Rows[m_nWholeRecIndex]["出口总金额"] = dsChuKou.Tables[0].Rows[nChuKouRowIndex]["报关金额"];
                        dtNew.Rows[m_nWholeRecIndex]["系数A"] = dsChuKou.Tables[0].Rows[nChuKouRowIndex]["系数A"];
                        dtNew.Rows[m_nWholeRecIndex]["设定开票汇率"] = dsChuKou.Tables[0].Rows[nChuKouRowIndex]["开票汇率"];
                        if (dtNew.Rows[m_nWholeRecIndex]["设定开票汇率"].ToString() != "")
                        {
                            dtNew.Rows[m_nWholeRecIndex]["开票本金"]
                                = (Decimal)dtNew.Rows[m_nWholeRecIndex]["设定开票汇率"] * (Decimal)dtNew.Rows[m_nWholeRecIndex]["出口总金额"];
                        }
                        //Decimal dtBackPoint = (Decimal)dsChuKou.Tables[0].Rows[nChuKouRowIndex]["退税点"];
                        if (lstMoreBackTaxPointContract.Contains(dsChuKou.Tables[0].Rows[nChuKouRowIndex]["合同号"].ToString()))
                        {
                            DataSet dsTemp = m_bllBGCKHTTab.CountAllCKHTMXForBackTax(dsChuKou.Tables[0].Rows[nChuKouRowIndex]["合同号"].ToString());
                            FillBackTaxPointJinE(dsTemp, dtNew.Rows[m_nWholeRecIndex]);
                        }
                        else
                        {
                            FillBackTaxPointJinETrue(DicContractNo2SingleBackTaxPoint[dsChuKou.Tables[0].Rows[nChuKouRowIndex]["合同号"].ToString()]
                                , (Decimal)dsChuKou.Tables[0].Rows[nChuKouRowIndex]["报关金额"], dtNew.Rows[m_nWholeRecIndex]);
                        }
                    }
                    else if (nChuKouRowIndexRec < nChuKouRowIndex)//如果上次收款>出口金额且因此换行
                    {
                        nLastUltragridChuKouRowIndexRec = m_nWholeRecIndex;
                        dtChuKouJinETemp = (Decimal)dsChuKou.Tables[0].Rows[nChuKouRowIndex]["报关金额"];
                        nChuKouRowIndexRec = nChuKouRowIndex;

                        DataRow dr = dtNew.NewRow();
                        dtNew.Rows.Add(dr);

                        dtNew.Rows[m_nWholeRecIndex]["合同号"] = dsChuKou.Tables[0].Rows[nChuKouRowIndex]["合同号"];
                        dtNew.Rows[m_nWholeRecIndex]["申报日期"] = dsChuKou.Tables[0].Rows[nChuKouRowIndex]["申报日期"];
                        dtNew.Rows[m_nWholeRecIndex]["币制"] = dsChuKou.Tables[0].Rows[nChuKouRowIndex]["币制"];
                        dtNew.Rows[m_nWholeRecIndex]["出口总金额"] = dsChuKou.Tables[0].Rows[nChuKouRowIndex]["报关金额"];
                       // Decimal dtBackPoint = (Decimal)dsChuKou.Tables[0].Rows[nChuKouRowIndex]["退税点"];
                        dtNew.Rows[m_nWholeRecIndex]["系数A"] = dsChuKou.Tables[0].Rows[nChuKouRowIndex]["系数A"];
                        dtNew.Rows[m_nWholeRecIndex]["设定开票汇率"] = dsChuKou.Tables[0].Rows[nChuKouRowIndex]["开票汇率"];
                        if (dtNew.Rows[m_nWholeRecIndex]["设定开票汇率"].ToString() != "")
                        {
                            dtNew.Rows[m_nWholeRecIndex]["开票本金"]
                                = (Decimal)dtNew.Rows[m_nWholeRecIndex]["设定开票汇率"] * (Decimal)dtNew.Rows[m_nWholeRecIndex]["出口总金额"];
                        }
                        if (lstMoreBackTaxPointContract.Contains(dsChuKou.Tables[0].Rows[nChuKouRowIndex]["合同号"].ToString()))
                        {
                            DataSet dsTemp = m_bllBGCKHTTab.CountAllCKHTMXForBackTax(dsChuKou.Tables[0].Rows[nChuKouRowIndex]["合同号"].ToString());
                            FillBackTaxPointJinE(dsTemp, dtNew.Rows[m_nWholeRecIndex]);
                        }
                        else
                        {
                            FillBackTaxPointJinETrue(DicContractNo2SingleBackTaxPoint[dsChuKou.Tables[0].Rows[nChuKouRowIndex]["合同号"].ToString()]
                               , (Decimal)dsChuKou.Tables[0].Rows[nChuKouRowIndex]["报关金额"], dtNew.Rows[m_nWholeRecIndex]);
                        }
                    }
                    else//如果上次收款<出口金额，设置出口额=剩余的出口额
                    {
                        dtChuKouJinETemp = dtChuKouJinEKeepRec;
                        dtChuKouJinEKeepRec = 0;
                        DataRow dr = dtNew.NewRow();
                        dtNew.Rows.Add(dr);
                    }


                    ////如果收款是第一条记录
                    if (nRecvMoneyRowIndex == 0 && m_nWholeRecIndex == 0)
                    {
                        dtRecvMoneyTemp = (Decimal)dsRecvMoney.Tables[0].Rows[nRecvMoneyRowIndex]["扣费后折算为USD"];
                    }
                    else if (nRecvMoneyRowIndexRec < nRecvMoneyRowIndex)//如果上次收款<出口金额且因此换行
                    {
                        dtRecvMoneyTemp = (Decimal)dsRecvMoney.Tables[0].Rows[nRecvMoneyRowIndex]["扣费后折算为USD"];
                        nRecvMoneyRowIndexRec = nRecvMoneyRowIndex;
                    }
                    else//如果上次收款>出口金额，设置收款额=剩余的收款额
                    {
                        dtRecvMoneyTemp = dtRecvMoneyKeepRec;
                        dtRecvMoneyKeepRec = 0;
                    }
                    //dtChuKouJinETemp = (Decimal)dsChuKou.Tables[0].Rows[nChuKouRowIndex]["报关金额"];
                    //dtRecvMoneyTemp = (Decimal)dsRecvMoney.Tables[0].Rows[nRecvMoneyRowIndex]["扣费后折算为USD"];

                    //收款够就全堆上出口金额，收款剩下的记下来，同时换行，取下一个合同号
                    if (dtRecvMoneyTemp > dtChuKouJinETemp)
                    {
                        dtNew.Rows[m_nWholeRecIndex]["收款币种"] = dsRecvMoney.Tables[0].Rows[nRecvMoneyRowIndex]["币种名称"]; //收款够就全堆上出口金额
                        dtNew.Rows[m_nWholeRecIndex]["折算为USD"] = dtChuKouJinETemp;//收款够就全堆上出口金额
                        dtNew.Rows[m_nWholeRecIndex]["结汇日期"] = dsRecvMoney.Tables[0].Rows[nRecvMoneyRowIndex]["结汇日期"];
                        
                        string[] strTemp = dsRecvMoney.Tables[0].Rows[nRecvMoneyRowIndex]["汇率公式"].ToString().Split('/');
                        
                        dtNew.Rows[m_nWholeRecIndex]["RMB汇率"]
                                                   = strTemp.Length > 1 ?
                                                    Convert.ToDecimal(strTemp[1]) : (Decimal)dsRecvMoney.Tables[0].Rows[nRecvMoneyRowIndex]["RMB汇率"];

                        dtNew.Rows[m_nWholeRecIndex]["收款RMB汇率"] = (Decimal)dsRecvMoney.Tables[0].Rows[nRecvMoneyRowIndex]["RMB汇率"];
                        dtNew.Rows[m_nWholeRecIndex]["付本日期"] = dsRecvMoney.Tables[0].Rows[nRecvMoneyRowIndex]["付本日期"];
                        dtNew.Rows[m_nWholeRecIndex]["已付货款"] = dtChuKouJinETemp * (Decimal)dtNew.Rows[m_nWholeRecIndex]["RMB汇率"];
                        if (dtNew.Rows[m_nWholeRecIndex]["开票本金"].ToString() != ""
                            && dtNew.Rows[m_nWholeRecIndex]["已付货款"].ToString() != "")
                        {
                            dtNew.Rows[m_nWholeRecIndex]["补RMB"] = (Decimal)dtNew.Rows[m_nWholeRecIndex]["开票本金"] - (Decimal)dtNew.Rows[m_nWholeRecIndex]["已付货款"];
                        }


                        dtRecvMoneyKeepRec = dtRecvMoneyTemp - dtChuKouJinETemp;//收款剩下的记下来
                        nChuKouRowIndex++;//换行，取下一个合同号
                        //以下为处理退税
                        // ProcessBackTax(dtNew, rows, nLastUltragridChuKouRowIndexRec, m_nWholeRecIndex);
                    }
                    else//收款不够，有多少堆多少，出口额剩余的记下来，同时换行，取下一个收款。
                    {
                        //收款不够，有多少堆多少
                        dtNew.Rows[m_nWholeRecIndex]["收款币种"] = dsRecvMoney.Tables[0].Rows[nRecvMoneyRowIndex]["币种名称"]; //收款够就全堆上出口金额

                        dtNew.Rows[m_nWholeRecIndex]["折算为USD"] = dtRecvMoneyTemp;
                        dtChuKouJinEKeepRec = dtChuKouJinETemp - dtRecvMoneyTemp;//出口额剩余的记下来
                        dtNew.Rows[m_nWholeRecIndex]["结汇日期"] = dsRecvMoney.Tables[0].Rows[nRecvMoneyRowIndex]["结汇日期"];
                        string[] strTemp = dsRecvMoney.Tables[0].Rows[nRecvMoneyRowIndex]["汇率公式"].ToString().Split('/');
                        
                        dtNew.Rows[m_nWholeRecIndex]["RMB汇率"]
                           = strTemp.Length > 1 ?
                            Convert.ToDecimal(strTemp[1]) : (Decimal)dsRecvMoney.Tables[0].Rows[nRecvMoneyRowIndex]["RMB汇率"];
                        dtNew.Rows[m_nWholeRecIndex]["收款RMB汇率"] = (Decimal)dsRecvMoney.Tables[0].Rows[nRecvMoneyRowIndex]["RMB汇率"];
                        dtNew.Rows[m_nWholeRecIndex]["付本日期"] = dsRecvMoney.Tables[0].Rows[nRecvMoneyRowIndex]["付本日期"];
                        dtNew.Rows[m_nWholeRecIndex]["已付货款"] = dtRecvMoneyTemp * (Decimal)dtNew.Rows[m_nWholeRecIndex]["RMB汇率"];
                        if (dtNew.Rows[m_nWholeRecIndex]["开票本金"].ToString() != ""
                              && dtNew.Rows[m_nWholeRecIndex]["已付货款"].ToString() != "")
                        {
                            dtNew.Rows[m_nWholeRecIndex]["补RMB"] = (Decimal)dtNew.Rows[m_nWholeRecIndex]["开票本金"] - (Decimal)dtNew.Rows[m_nWholeRecIndex]["已付货款"];
                        }
                        nRecvMoneyRowIndex++;//换行，取下一个收款
                    }
                    //不能放在这里，会导致最后一个结汇日期不对
                   // dtNew.Rows[m_nWholeRecIndex]["结汇日期"] = dsRecvMoney.Tables[0].Rows[nRecvMoneyRowIndex]["结汇日期"];

                    dtFinalRecvTemp = dtRecvMoneyKeepRec;
                    m_nWholeRecIndex++;

                    if (m_nWholeRecIndex > 0)
                        ProcessBackTax(dtNew, alInvoice
                            , dsInvoice.Tables[0], alInvoiceIndex
                            , nFormulaSelector, dtFactorA, dsRecvMoney.Tables[0].Rows[dtRecvMoneyTemp > dtChuKouJinETemp ? nRecvMoneyRowIndex : nRecvMoneyRowIndex - 1]);
                }

                if (dtFinalRecvTemp > 0)
                {
                    DataRow dr = dtNew.NewRow();
                    dtNew.Rows.Add(dr);
                    dtNew.Rows[m_nWholeRecIndex]["折算为USD"] = dtFinalRecvTemp;
                }
                //出口还有
                if (nChuKouRowIndex + 1 < dsChuKou.Tables[0].Rows.Count)
                {
                    nChuKouRowIndex++;
                    while (nChuKouRowIndex < dsChuKou.Tables[0].Rows.Count)
                    {
                        DataRow dr = dtNew.NewRow();
                        dtNew.Rows.Add(dr);

                        dtNew.Rows[m_nWholeRecIndex]["合同号"] = dsChuKou.Tables[0].Rows[nChuKouRowIndex]["合同号"];
                        dtNew.Rows[m_nWholeRecIndex]["申报日期"] = dsChuKou.Tables[0].Rows[nChuKouRowIndex]["申报日期"];
                        dtNew.Rows[m_nWholeRecIndex]["币制"] = dsChuKou.Tables[0].Rows[nChuKouRowIndex]["币制"];
                        dtNew.Rows[m_nWholeRecIndex]["出口总金额"] = dsChuKou.Tables[0].Rows[nChuKouRowIndex]["报关金额"];
                       // Decimal dtBackPoint = (Decimal)dsChuKou.Tables[0].Rows[nChuKouRowIndex]["退税点"];
                        dtNew.Rows[m_nWholeRecIndex]["系数A"] = dsChuKou.Tables[0].Rows[nChuKouRowIndex]["系数A"];
                        dtNew.Rows[m_nWholeRecIndex]["设定开票汇率"] = dsChuKou.Tables[0].Rows[nChuKouRowIndex]["开票汇率"];
                        if (dtNew.Rows[m_nWholeRecIndex]["设定开票汇率"].ToString() != "")
                        {
                            dtNew.Rows[m_nWholeRecIndex]["开票本金"]
                                = (Decimal)dtNew.Rows[m_nWholeRecIndex]["设定开票汇率"] * (Decimal)dtNew.Rows[m_nWholeRecIndex]["出口总金额"];
                        } 
                        if (lstMoreBackTaxPointContract.Contains(dsChuKou.Tables[0].Rows[nChuKouRowIndex]["合同号"].ToString()))
                        {
                            DataSet dsTemp = m_bllBGCKHTTab.CountAllCKHTMXForBackTax(dsChuKou.Tables[0].Rows[nChuKouRowIndex]["合同号"].ToString());
                            FillBackTaxPointJinE(dsTemp, dtNew.Rows[m_nWholeRecIndex]);
                        }
                        else
                        {
                            FillBackTaxPointJinETrue(DicContractNo2SingleBackTaxPoint[dsChuKou.Tables[0].Rows[nChuKouRowIndex]["合同号"].ToString()]
                               , (Decimal)dsChuKou.Tables[0].Rows[nChuKouRowIndex]["报关金额"], dtNew.Rows[m_nWholeRecIndex]);
                        }
                        m_nWholeRecIndex++;
                        nChuKouRowIndex++;
                    }
                }
            }
            catch (Exception ex)
            {
            }

            //如果此时恰好都结束了
            //if (nChuKouRowIndex == dsChuKou.Tables[0].Rows.Count
            //    && nRecvMoneyRowIndex == dsRecvMoney.Tables[0].Rows.Count)
            //{
            //    DataRow dr = dtNew.NewRow();
            //    dtNew.Rows.Add(dr);
            //    dtNew.Rows[m_nWholeRecIndex]["出口总金额"] = dtChouKouTotal;
            //}
            ////收款还有
            //else if (nChuKouRowIndex == dsChuKou.Tables[0].Rows.Count)
            //{

            //}
        }

        private void ultraGrid1_MouseDown(object sender, MouseEventArgs e)
        {
            UltraGrid grid = (UltraGrid)sender;
            UIElement element = grid.DisplayLayout.UIElement.LastElementEntered;
            if (element == null)
                return;
            Infragistics.Win.UltraWinGrid.ColumnHeader columnHeader = element.GetContext(typeof(Infragistics.Win.UltraWinGrid.ColumnHeader)) as Infragistics.Win.UltraWinGrid.ColumnHeader;
            if (columnHeader != null)
            {
                string str = columnHeader.Caption;
               // string strtype = grid.Rows[0].Cells[str].GetType().ToString();
                if (str != "出口总金额" && str != "折算为USD" && str != "付税本金")
                    return;
                Infragistics.Win.UltraWinGrid.UltraGridRow[] ugr = ultraGrid1.Rows.GetFilteredInNonGroupByRows();
                if (ugr.Length <= 0)
                {
                    return;
                }
                Decimal dtTemp = 0;
                for (int i = 0; i < ugr.Length; i++)
                {
                    string strTemp = ugr[i].Cells[str].Value.ToString();
                    if (strTemp != "")
                        dtTemp += Convert.ToDecimal(ugr[i].Cells[str].Value.ToString());
                }
                this.textBoxTotal.Text = dtTemp.ToString();


                //if(bool f=age is int;


                // Set the grid's tooltip here
                // Debug.WriteLine("ToolTip");
            }
            else
            {
                // Set the grid's tooltip to null. 
                //  Debug.WriteLine("null");
            }
        }
        private void ultraGrid1_AfterCellActivate(object sender, EventArgs e)
        {
            int iIndex = this.ultraGrid1.ActiveCell.Row.Index;
            if (iIndex < 0)
                return;
            // m_nDelIndex = ultraGrid1.ActiveRow.Index;
            if (m_bSumStart)
            {
                if (this.ultraGrid1.ActiveCell.Appearance.BackColor.Name == "0")
                {
                    this.ultraGrid1.ActiveCell.Appearance.BackColor = Color.Aqua;
                }
                else
                {
                    this.ultraGrid1.ActiveCell.Appearance.BackColor = Color.FromName("0");
                }
            }
        }

        private void buttonSumStart_Click_1(object sender, EventArgs e)
        {
            m_bSumStart = true;
            Infragistics.Win.UltraWinGrid.UltraGridRow[] ugr = ultraGrid1.Rows.GetFilteredInNonGroupByRows();
            for (int i = 0; i < ugr.Length; i++)
            {
                for (int j = 0; j < ugr[i].Cells.Count; j++)
                {
                    if (ugr[i].Cells[j].Appearance.BackColor == Color.Aqua)
                    {
                        ugr[i].Cells[j].Appearance.BackColor = Color.FromName("0");
                    }
                }
            }
        }

        private void buttonSumStop_Click_1(object sender, EventArgs e)
        {
            try
            {
                Decimal dtTotal = 0;
                Infragistics.Win.UltraWinGrid.UltraGridRow[] ugr = ultraGrid1.Rows.GetFilteredInNonGroupByRows();
                for (int i = 0; i < ugr.Length; i++)
                {
                    for (int j = 0; j < ugr[i].Cells.Count; j++)
                    {
                        if (ugr[i].Cells[j].Appearance.BackColor == Color.Aqua)
                        {
                            Decimal dtTemp = Convert.ToDecimal(ugr[i].Cells[j].Value.ToString());
                            dtTotal += dtTemp;
                            //ugr[i].Cells[j].Appearance.BackColor = Color.FromName("0");
                        }
                    }
                }

                this.textBoxTotal.Text = dtTotal.ToString();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }

        private void buttonExportToExcel_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)ultraGrid1.DataSource;

            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Filter = "Excel文件(*.xls)|*.xls";
                    string outFile = "";

                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        outFile = sfd.FileName;
                    }
                    else
                    {
                        return;
                    }

                    ultraGridExcelExporter1.Export(ultraGrid1, outFile);
                }
            }
        }

        private void ultraGrid1_InitializeLayout(object sender, InitializeLayoutEventArgs e)
        {
            this.ultraGrid1.DisplayLayout.UseFixedHeaders = true;
            ultraGrid1.DisplayLayout.Bands[0].Columns["合同号"].Header.Fixed = true;
            ultraGrid1.DisplayLayout.Bands[0].Columns["申报日期"].Header.Fixed = true;
            ultraGrid1.DisplayLayout.Bands[0].Columns["币制"].Header.Fixed = true;
            ultraGrid1.DisplayLayout.Bands[0].Columns["出口总金额"].Header.Fixed = true;

            ultraGrid1.DisplayLayout.Override.FixedHeaderIndicator = FixedHeaderIndicator.None;  // 不显示小图标
            

            if (this.checkBox1.Checked == true)
                ultraGrid1_InitializeRowFilter(e);
            else
                ClassUltraGridCommonSet.ultraGrid1_InitializeRowFilter(e);
            ClassUltraGridCommonSet.LocalPrintPreveiw();
        }
        public static void ultraGrid1_InitializeRowFilter(Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            //ultraGrid1.DisplayLayout.Override.RowSizing = RowSizing.AutoFree;
            //foreach (UltraGridColumn ugc in ultraGrid1.DisplayLayout.Bands[0].Columns)
            //    ugc.PerformAutoResize();
            // FILTER ROW FUNCTIONALITY RELATED ULTRAGRID SETTINGS
            //e.Layout.Override.RowFilterAction = RowFilterAction.DisableFilteredOutRows;
            // ----------------------------------------------------------------------------------
            // Enable the the filter row user interface by setting the FilterUIType to FilterRow.
            e.Layout.Override.FilterUIType = FilterUIType.FilterRow;
            //e.Layout.Override.RowFilterMode = RowFilterMode.AllRowsInBand;
            // FilterEvaluationTrigger specifies when UltraGrid applies the filter criteria typed 
            // into a filter row. Default is OnCellValueChange which will cause the UltraGrid to
            // re-filter the data as soon as the user modifies the value of a filter cell.
            e.Layout.Override.FilterEvaluationTrigger = FilterEvaluationTrigger.OnCellValueChange;
            //e.Layout.Override.RowFilterMode = RowFilterMode.AllRowsInBand;
            // By default the UltraGrid selects the type of the filter operand editor based on
            // the column's DataType. For DateTime and boolean columns it uses the column's editors.
            // For other column types it uses the Combo. You can explicitly specify the operand
            // editor style by setting the FilterOperandStyle on the override or the individual
            // columns.

            e.Layout.Override.FilterOperandStyle = FilterOperandStyle.DropDownList;

            // By default UltraGrid displays user interface for selecting the filter operator. 
            // You can set the FilterOperatorLocation to hide this user interface. This
            // property is available on column as well so it can be controlled on a per column
            // basis. Default is WithOperand. This property is exposed off the column as well.
            e.Layout.Override.FilterOperatorLocation = FilterOperatorLocation.WithOperand;

            // By default the UltraGrid uses StartsWith as the filter operator. You use
            // the FilterOperatorDefaultValue property to specify a different filter operator
            // to use. This is the default or the initial filter operator value of the cells
            // in filter row. If filter operator user interface is enabled (FilterOperatorLocation
            // is not set to None) then that ui will be initialized to the value of this
            // property. The user can then change the operator as he/she chooses via the operator
            // drop down.
            e.Layout.Override.FilterOperatorDefaultValue = FilterOperatorDefaultValue.StartsWith;

            // FilterOperatorDropDownItems property can be used to control the options provided
            // to the user for selecting the filter operator. By default UltraGrid bases 
            // what operator options to provide on the column's data type. This property is
            // avaibale on the column as well.
            //e.Layout.Override.FilterOperatorDropDownItems = FilterOperatorDropDownItems.All;

            // By default UltraGrid displays a clear button in each cell of the filter row
            // as well as in the row selector of the filter row. When the user clicks this
            // button the associated filter criteria is cleared. You can use the 
            // FilterClearButtonLocation property to control if and where the filter clear
            // buttons are displayed.
            e.Layout.Override.FilterClearButtonLocation = FilterClearButtonLocation.RowAndCell;

            // Appearance of the filter row can be controlled using the FilterRowAppearance proeprty.
            e.Layout.Override.FilterRowAppearance.BackColor = Color.LightYellow;

            // You can use the FilterRowPrompt to display a prompt in the filter row. By default
            // UltraGrid does not display any prompt in the filter row.
            e.Layout.Override.FilterRowPrompt = "Click here to filter data...";

            // You can use the FilterRowPromptAppearance to change the appearance of the prompt.
            // By default the prompt is transparent and uses the same fore color as the filter row.
            // You can make it non-transparent by setting the appearance' BackColorAlpha property 
            // or by setting the BackColor to a desired value.
            e.Layout.Override.FilterRowPromptAppearance.BackColorAlpha = Alpha.Opaque;

            // By default the prompt is spread across multiple cells if it's bigger than the
            // first cell. You can confine the prompt to a particular cell by setting the
            // SpecialRowPromptField property off the band to the key of a column.
            //e.Layout.Bands[0].SpecialRowPromptField = e.Layout.Bands[0].Columns[0].Key;

            // Display a separator between the filter row other rows. SpecialRowSeparator property 
            // can be used to display separators between various 'special' rows, including for the
            // filter row. This property is a flagged enum property so it can take multiple values.
            e.Layout.Override.SpecialRowSeparator = SpecialRowSeparator.FilterRow;

            // You can control the appearance of the separator using the SpecialRowSeparatorAppearance
            // property.
            e.Layout.Override.SpecialRowSeparatorAppearance.BackColor = Color.FromArgb(233, 242, 199);

            //   UltraGridBand band = e.Layout.Bands[0];
            //   band.ColumnFilters["原币金额"].FilterConditions.Clear();
            //   band.ColumnFilters["原币金额"].FilterConditions.Add(

            //FilterComparisionOperator.GreaterThan, 5);
            //   band.ColumnFilters["原币金额"].FilterConditions.Add(

            //FilterComparisionOperator.LessThan, 10);
            //   band.ColumnFilters["原币金额"].LogicalOperator = FilterLogicalOperator.And;
        }
    }
}
